const db = require('../..//db');

exports.addNewPayment = (orderId, orderState, amount, callback) => {
  const q = "INSERT INTO module2_payment SET ? ;";
  const values = {
    order_id: orderId,
    order_state: orderState,
    amount: amount,
  };

  db.query(q, values, (err, results) => {
    if (err) {
      callback(err);
    } else if (results.affectedRows !== 1) {
      callback(new Error("添加失败，请稍后再试！"));
    } else {
      callback(null, "添加成功！", 0);
    }
  });
};

//输入新状态，订单号，更新订单状态
exports.updatePaymentState = (orderId, newState, callback) => {
    const q = "UPDATE module2_payment SET order_state = ? WHERE order_id = ?";
    const values = [newState, orderId];
  
    db.query(q, values, (err, results) => {
      if (err) {
        callback(err);
      } else if (results.affectedRows !== 1) {
        callback(new Error("更新失败，请稍后再试！"));
      } else {
        callback(null, "更新成功！", 0);
      }
    });
  };
//输入新金额，订单号，更新订单金额
exports.updatePaymentAmount = (orderId, newAmount, callback) => {
    const q = "UPDATE module2_payment SET amount = ? WHERE order_id = ?;";
    const values = [newAmount, orderId];
  
    db.query(q, values, (err, results) => {
      if (err) {
        callback(err);
      } else if (results.affectedRows !== 1) {
        callback(new Error("更新失败，请稍后再试！"));
      } else {
        callback(null, "更新成功！", 0);
      }
    });
  };

// //输入订单号，查询订单信息
// exports.paymentIdSearch = (req, res) => {
//     const q = "Select * from city WHERE id = ?";

//     const values = req.params.id;
//     db.query(q, values, (err, results) => {
//         if (err) return res.cc(err);
//         //if (results.affectedRows !== 1) return res.cc("更新失败，请稍后再试！");
//         //res.cc("更新成功！", 0);
//     });
// };

exports.getPaymentAmount = (orderId, callback) => {
  const q = "SELECT amount FROM module2_payment WHERE order_id = ?";
  const values = [orderId];

  db.query(q, values, (err, results) => {
    if (err) {
      callback(err);
    } else if (results.length === 0) {
      callback(new Error("未找到该订单的付款记录！"));
    } else {
      const amount = results[0].amount;
      callback(null,amount);
    }
  });
};